package com.gitee.fanx.sample.otpauth.controller;

import com.gitee.fanx.sample.otpauth.common.TotpAuthenticator;
import com.gitee.fanx.sample.otpauth.entity.User;
import com.gitee.fanx.sample.otpauth.service.UserService;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Writer;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author fanhang
 */
@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;

	/**
	 * 注册
	 * @param phone
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/register")
	public User register(@RequestParam("phone") String phone) throws Exception {
		User user = userService.register(phone);
		return user;
	}

	/**
	 * 生成二维码
	 * @param phone   phone
	 * @param response
	 * @throws Exception
	 */
	@GetMapping("/qrCode")
	public void qrCode(String phone, HttpServletResponse response) throws Exception{
		String uri = userService.generateTotpauthUri(phone);
		response.setContentType("image/png");
		try (OutputStream out = response.getOutputStream()) {
			System.out.println(uri);
			try {
				Writer writer = new QRCodeWriter();
				BitMatrix bitMatrix = writer.encode(uri, BarcodeFormat.QR_CODE, 350, 350);
				MatrixToImageWriter.writeToStream(bitMatrix, "PNG", out);
			} catch (WriterException e) {
				throw new IOException(e.getMessage());
			}
		}
	}

	/**
	 * 验证
	 * @param phone
	 * @param code
	 * @retur
	 */
	@GetMapping("/verify")
	public Map<String, Integer> verify(String phone, Integer code) {
		int validIndex = userService.verify(phone, code);
		System.out.println(validIndex);
		Assert.state(validIndex >= 0, "验证码错误");
		return Collections.singletonMap("validIndex", validIndex);
	}

	@GetMapping("/dataView")
	@ResponseBody
	public List<User> dataView()throws Exception{
		return userService.getAll();
	}

}
